{% extends "admin/base_site.html" %}
{% load i18n admin_urls static %}

{% block extrastyle %}
{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}">
<style>
  .edit-form-container {
    max-width: 500px;
    margin: 20px auto;
    padding: 20px;
    background: white;
    border-radius: 5px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  }

  .form-row {
    margin-bottom: 15px;
  }

  .form-row label {
    display: block;
    font-weight: bold;
    margin-bottom: 5px;
  }

  .form-row input[type="number"] {
    width: 100%;
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 3px;
  }

  .form-actions {
    margin-top: 20px;
    text-align: right;
  }
</style>
{% endblock %}

{% block content %}
<div class="edit-form-container">
  <h1>{{ title }}</h1>

  <form id="editItemForm">
    {% csrf_token %}
    <input type="hidden" name="item_id" value="{{ item.cart_id }}">

    <div class="form-row">
      <label>用户:</label>
      <input type="text" value="{{ item.user.username }} (ID: {{ item.user.user_id }})" disabled>
    </div>

    <div class="form-row">
      <label>商品:</label>
      <input type="text" value="{{ item.goods.goods_name }}" disabled>
    </div>

    <div class="form-row">
      <label for="goods_num">商品数量:</label>
      <input type="number" id="goods_num" name="goods_num" value="{{ item.goods_num }}" min="1" required>
    </div>

    <div class="form-row">
      <label for="selected">
        <input type="checkbox" id="selected" name="selected" {% if item.selected %}checked{% endif %}>
        是否选中
      </label>
    </div>

    <div class="form-actions">
      <button type="button" class="button" onclick="window.history.back()">取消</button>
      <button type="submit" class="button default">保存</button>
    </div>
  </form>
</div>

<script>
  document.getElementById('editItemForm').addEventListener('submit', function (e) {
    e.preventDefault();

    const formData = new FormData(this);
    formData.append('selected', document.getElementById('selected').checked);

    fetch('{% url "admin:shoppingcart_update_item" %}', {
      method: 'POST',
      body: formData,
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
      }
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          alert('更新成功');
          window.location.reload();
        } else {
          alert('更新失败: ' + data.message);
        }
      })
      .catch(error => {
        alert('发生错误: ' + error);
      });
  });
</script>
{% endblock %}